package org.phalanx.server.properties.xml;

import java.util.ArrayList;
import java.util.Hashtable;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class PhalanxConfigFileHandler extends DefaultHandler {
	ArrayList<String> configClassName = new ArrayList<String>();
	Boolean isTagClosed = new Boolean(true);
	Hashtable<String,String> genericKeyValue = new Hashtable<String,String>();
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String propertyValue;
		
		if (isTagClosed.equals(false)){
			propertyValue = new String(ch, start, length);
			genericKeyValue.put(getConfigClassName(), propertyValue);
		}
		super.characters(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		
		configClassName.remove(configClassName.size() - 1);
		isTagClosed = new Boolean(true);
		super.endElement(uri, localName, name);
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		configClassName.add(localName);
		isTagClosed = new Boolean(false);
		super.startElement(uri, localName, name, attributes);
	}
	
	private String getConfigClassName(){
		String configClassNameURI = new String();
		
		for (int i = 0; i < configClassName.size() - 1; i++){
			configClassNameURI += configClassName.get(i) + ".";
		}
		configClassNameURI += configClassName.get(configClassName.size() - 1);
		
		return configClassNameURI;
	}
	
	public Hashtable<String,String> getHashtable(){
		return genericKeyValue;
	}
	
	
}
